package com.ai.util;


import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.nio.charset.Charset;

/**
 * 调用远程服务器shell脚本
 * @Author jiaok
 * @Date 2024-05-27 11:33
 */
@Slf4j
@Data
@Setter
@Getter
public class SSHClient {

    /**
     * 服务器ip
     */
    private String ip;

    /**
     * 服务器用户名
     */
    private String userName;

    /**
     * 服务器密码
     */
    private String password;

    /**
     * shell脚本路径
     */
    private String execShellPath;

    /**
     * 默认字符集
     */
    private String charset = Charset.defaultCharset().toString();

    private static final int TIME_OUT = 1000 * 5 * 60;

    ChannelExec channelExec = null;
    Session session = null;


    /**
     * 远程连接
     */

    public SSHClient(String ip, String userName, String password) {
        this.ip = ip;
        this.userName = userName;
        this.password = password;
    }


   public  void execShell(){
       try {
           JSch jSch = new JSch();
           Session session = jSch.getSession(userName, ip, 22);
           session.setPassword(password);
           session.setConfig("StrictHostKeyChecking", "no");
           session.connect();

           channelExec = (ChannelExec) session.openChannel("exec");
           channelExec.setCommand(execShellPath);
           InputStream in = channelExec.getInputStream();
           channelExec.connect();

           BufferedReader reader = new BufferedReader(new InputStreamReader(in));
           String line;

           log.info("=========================== shell脚本输出内容  ===========================");
           while ((line = reader.readLine()) != null) {

               log.info("=========================== originShell:{}   ===========================",line);

           }

           channelExec.disconnect();
           session.disconnect();

       } catch (JSchException | IOException e) {
           log.error("=============================  ssh连接建立失败  ===============================");
           log.error(e.getMessage());
           throw new RuntimeException(e);
       }finally {
           if (channelExec != null){
               channelExec.disconnect();
           }
           if (session != null){
               session.disconnect();
           }
       }

   }

    public static void main(String[] args) {
        SSHClient sshClient = new SSHClient("192.168.8.194", "jiaokang", "jiaokang");
        sshClient.setExecShellPath("/usr/local/test_shell.sh");
        sshClient.execShell();
    }
}
